package com.unittec.drainage.gateway.filter;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletRequest;

import com.unittec.drainage.gateway.common.GateWayConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.service.WebSocketServer;

/**
 * @author wuxinwei
 */
@Component
public class WebSocketFilter extends ZuulFilter {

    @Autowired
    Log log;

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        try {
            String serviceName = (String)ctx.get(GateWayConstants.SERVICEMETHED);
            if (GateWayConstants.INTERFACE_125807.equals(serviceName)) {
                HttpServletRequest request = ctx.getRequest();
                InputStream in = request.getInputStream();
                String reqBody = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
                log.sysInfoLog("WebSocketFilter run", "reqBody :" + reqBody);
                JSONObject json = JSONObject.parseObject(reqBody);
                JSONObject content = json.getJSONObject("content");
                if (content != null) {
                    InputStream out = ctx.getResponseDataStream();
                    String outBody = StreamUtils.copyToString(out, StandardCharsets.UTF_8);
                    log.sysInfoLog("WebSocketFilter run", "outBody :" + outBody);
                    String userId = content.getString("user_id");
                    String websocketMsgType = content.getString("websocket_msg_type");
                    if (StringUtils.isBlank(websocketMsgType)) {
                        websocketMsgType = "BUSINESS";
                    }
                    JSONObject messageJson =
                        JSON.parseObject(outBody) == null ? new JSONObject() : JSON.parseObject(outBody);
                    messageJson.put("websocket_msg_type", websocketMsgType);
                    // 当前用户发送推送
                    if (StringUtils.isBlank(userId)) {
                        WebSocketServer.sendMessageByAll();
                    } else {
                        WebSocketServer.sendMessageByUserId(userId, messageJson.toJSONString());
                    }

                }
            }
        } catch (Exception e) {
            log.sysErrLog("WebSocketFilter run", "发送webSocket消息错误", e);
        }
        return null;

    }

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 2;
    }

}
